package com.njust.controller;

import com.njust.Util.JwtUtil;
import com.njust.context.BaseContext;
import com.njust.domain.dto.UserLoginDTO;
import com.njust.domain.dto.UserSignInDTO;
import com.njust.domain.po.User;
import com.njust.domain.vo.UserLoginVO;
import com.njust.domain.vo.UserSignInVO;
import com.njust.domain.vo.UserVO;
import com.njust.result.Result;
import com.njust.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Author Imak
 * @Date 2024/10/18 14:29
 * @用户账号相关接口
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 登录接口
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        UserLoginVO userLoginVO=userService.login(userLoginDTO);
        log.info("用户登录，{}",userLoginVO);
        return Result.success(userLoginVO,"登录成功");
    }

    /**
     * 退出登录接口
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        Integer uId=BaseContext.getCurrentId();
        log.info("用户退出登录，uId={}",uId);
        userService.logout(uId);
        //退出账号 及时remove缓存
        BaseContext.removeCurrentId();
        return Result.success("退出账号成功");
    }
    /**
     * 注册接口
     * @param userSignInDTO
     * @return
     */
    @PostMapping("/signin")
    public Result<UserSignInVO> signIn(@RequestBody UserSignInDTO userSignInDTO){
        log.info("用户注册，{}",userSignInDTO);
        User user = userService.sign(userSignInDTO);
        UserSignInVO userSignInVO = UserSignInVO.builder().uId(user.getUId()).build();
        return Result.success(userSignInVO, "注册成功");
    }
    /**
     * 注销账号接口
     * @return
     */
    @DeleteMapping("/deleteAccount")
    public Result<String> deleteAcc(){
        Integer uId = BaseContext.getCurrentId();
        userService.deleteAcc(uId);
        log.info("账号已被注销,id={}",uId);
        //注销账号 及时remove缓存
        BaseContext.removeCurrentId();
        return Result.success("注销账号成功");

    }

    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<UserVO> userInfo(){
        Integer uId=BaseContext.getCurrentId();
        UserVO userVO=userService.userInfo(uId);
        return Result.success(userVO);
    }
}
